<template>
	<view>
		<nav-bar   fontColor="#FFFFFF" title="拉动单"></nav-bar>

		<uni-group mode="card">
			<qiun-title-bar title="上传拉动单" />
			<view style="height: 60rpx;">
				<view style="float: left;font-size: 32rpx;">最多上传5个文件</view>
				<view style="float: right;font-size: 32rpx;color: #afafaf;">{{fileList.length}}/5</view>
			</view>
			<view style="height: 80rpx;">
				<button @tap="onUpload" type="primary" size="mini">选择文件</button>
			</view>

			<view v-for="(item,index) in fileList"
				style="height: 60rpx;width: 100%;margin-top: 10rpx;border: 1px solid #EEEEEE;">
				<view style="float: left;line-height: 60rpx;padding-left: 20rpx;">{{item.fileName}}</view>
				<view @click="removeFile(index)" style="float: right;margin:15rpx 10rpx;">
					X
				</view>
			</view>
		</uni-group>
		<!-- <view style="" class="input_form_box borderCss">
			<view class="input_box btm_line">
				<view class="name required">附件类型</view>
				<picker :range="typeList" :value="index" @change="onTypeListChange">
					<view class="select_info">
						<view class="value" v-if="attachType">{{attachType}}</view>
						<view class="select" v-else>请选择</view>
					</view>
				</picker>
			</view>
		</view> -->
		<!-- <view style="height: 100rpx;">
			<view style="position: fixed;bottom: 20rpx;width: 100%;">
				<button @click="submit()"
					style="background: #3B5DE0;color: #FFFFFF;border-radius: 10rpx;width: 90%;height: 100rpx;margin: 0 auto;">提交</button>
			</view>
		</view> -->
		<l-file ref="lFile" :logo="logo" @up-success="onSuccess"></l-file>
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="3000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import htzImageUpload from '@/components/htz-image-upload/htz-image-upload-show.vue'
	export default {
		components: {
			htzImageUpload,
		},
		data() {
			return {
				serialNo: '',
				imageData: [],
				attachType: '物品照片',
				index: 0,
				typeList: ["物品照片", "情况说明"],
				logo: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F00%2F07%2F155788a6d8a5c42.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619847627&t=2da40b583002205c204d980b54b35040',
				fileList: [],
				msgType: 'success',
				messageText: '这是一条成功提示'
			}
		},
		onLoad(e) {
			this.serialNo = e.id
		},
		methods: {
			messageToggle(type,msg) {
				this.msgType = type
				this.messageText = msg
				this.$refs.message.open();
			},
			onTypeListChange(e) {
				this.index = e.target.value
				this.attachType = this.typeList[this.index]
			},
			removeFile(e) {
				console.log(e)
				this.fileList.splice(e, 1)
				console.log(this.fileList)
			},
			ceshiChooseSuccess(tempFilePaths, e) { //选择图片返回
				console.log('ceshiChooseSuccess', tempFilePaths, e);
				// this.imageData=this.imageData.concat(tempFilePaths)

				//this.imageData.push(...tempFilePaths)
				/****************
				以下代码是自定义上传逻辑，仅供参考
				***************/
				this.tempFilePaths = tempFilePaths
				// this.imageData.push(tempFilePaths[0]);
				this.imgUpload(tempFilePaths);
				console.log(tempFilePaths)
				/*******************************/
			},
			imgUpload(tempFilePaths) {
				if (!tempFilePaths) {
					uni.showToast({
						title: '请上传视频或者照片！',
						position: 'center',
						icon: 'error'
					});
					return
				}
				uni.showLoading({
					title: '上传中'
				});
				console.log('imgUpload', tempFilePaths)
				let uploadImgs = [];
				tempFilePaths.forEach((item, index) => {
					uploadImgs.push(new Promise((resolve, reject) => {
						console.log(index, item)
						uni.uploadFile({
							url: "http://192.168.1.15:39527/sys/file/upload", //仅为示例，非真实的接口地址
							filePath: item,
							// header:{
							// 	'Authorization':'Bearer ' + uni.getStorageSync('token')
							// },
							name: 'file',
							success: (uploadFileRes) => {
								console.log('uploadFileRes', uploadFileRes)
								resolve(uploadFileRes);
								var _res = JSON.parse(uploadFileRes.data);
								if (_res.code == 200) {
									console.log(_res.data)
									// let str = _res.data
									// let fileType = str.lastIndexOf(".")
									// str = str.substring(fileType + 1, str.length);
									// console.log(str)
									// this.imageData.push(
									// 	'http://localhost:39528/' + _res.data);
									this.imageData.push(_res.data)
									console.log('推送jpeg进数组')
									// this.submit();
								}
							},
							fail: (err) => {
								console.log(err);
								reject(err);
							},
							complete: () => {
								//uni.hideLoading();
							}
						});
					}))
				})
				Promise.all(uploadImgs) //执行所有需请求的接口
					.then((results) => {
						uni.hideLoading();
					})
					.catch((res, object) => {
						uni.hideLoading();
					});
			},
			submit() {
				if (this.attachType && this.fileList != '') {
					// let file = this.fileList.join(",")
					let fileData = [];
					let file = "";
					for (let i = 0; i < this.fileList.length; i++) {
						fileData.push(this.fileList[i].fileId)
					}
					file = fileData.join(",")
					let opt = {
						url: 'oms/tbRelatedItemAttach',
						method: 'POST'
					};
					let params = {
						serialNo: this.serialNo,
						attachType: '测试',
						name: file
					};
					console.log(params)
					this.$http.httpTokenRequest(opt, params).then(res => {
						console.log(res)
						if(res.data.code == 200){
							this.messageToggle('success',res.data.msg)
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 2000)
						}
						else{
							this.messageToggle('error',res.data.msg)
						}
					})
				} else {
					this.messageToggle('error','请输入完整数据')
				}
			},
			/* 上传 */
			onUpload() {
				if (this.fileList.length > 4) {
					this.messageToggle('error','最多只能上传5个文件')
					return
				}
				/**
				 * currentWebview: 当前webview
				 * url：上传接口地址
				 * name：附件key,服务端根据key值获取文件流，默认file,上传文件的key
				 * header: 上传接口请求头
				 */
				console.log('--------------------');
				this.$refs.lFile.upload({
					// #ifdef APP-PLUS
					//（app端必传）nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
					currentWebview: this.$mp.page.$getAppWebview(),
					// #endif
					//替换为你的上传接口地址
					url: 'http://115.29.199.1:18527/web/tbWmsMaterialDeliveryLine/importData',
					// 服务端接收附件的key
					name: 'file',
					//根据你接口需求自定义 (优先不传content-type,安卓端无法收到参数再传)
					header: {
						// "Content-Type": "application/json; charset=UTF-8",
						'Authorization':'Bearer ' + uni.getStorageSync('token'),
					},

					// 限制选择附件的大小上限，默认10M
					// maxSize: 20,

					// 若需要在body单独添加附件名或附件大小如下方式传入组件：
					// addName: '后端要的附件名称字段key,此处请勿写name的同值如(file)，会覆盖name',
					// addSize: '后端要的附件大小字段key'

					// body参数直接写key,value,如：
					// date: '2020-1-1',
					// key2: 'value2',
				});
			},
			onSuccess(res) {
				console.log('上传成功回调', res);
				this.fileList.push({
					fileName: res.fileName,
					fileId: res.data.data
				});
				console.log(JSON.stringify(this.fileList))
			}
		}
	}
</script>

<style>
	.borderCss {
		width: 95%;
		margin: 0 auto;
		border-radius: 10rpx;
		box-shadow: 3rpx 3rpx 3rpx 3rpx #EEEEEE;
	}
</style>
